@extends('manager._layouts.default')
 
@section('main')
 
    <h2>Edit product</h2>

    {{ Notification::showAll() }}

    {{ Form::model($product, 
        array(
            'method' => 'put', 
            'route' => array('manager.products.update', $product->id)
        )) 
    }}
        <div class="row">
            <div class="row col-lg-12">
                <div class="form-group col-lg-6">
                    <label for="name">Product Name</label>
                    <input type="text" id="name" name="name" value="{{$product->name}}" class="newproduct form-control">
                </div>
                <div class="form-group col-lg-3">
                    <label for="slug">Slug</label>
                    <i class="fa fa-fw fa-question-circle help" data-toggle="popover" data-placement="right" data-trigger="hover" data-content="This is the friendly URL of the page" data-container="body"></i>
                    <input type="text" id="slug" name="slug" value="{{$product->slug}}" class="form-control">
                </div>
            </div> 
        </div>

        <ul class="nav nav-tabs">
            <li class="active"><a href="#content" data-toggle="tab">Content</a></li>
            <li><a href="#general" data-toggle="tab">Settings</a></li>
            <li><a href="#images" data-toggle="tab">Images</a></li>
            <li><a href="#files" data-toggle="tab">Files</a></li>
            <li><a href="#relatedproducts" data-toggle="tab">Related Products</a></li>
        </ul>
        <div class="tab-content">
            <div class="tab-pane active" id="content">
                <label for="product-shortdescription">Short Description</label>
                <textarea name="shortdescription" id="product-shortdescription-editor" class="form-control">{{$product->shortdescription}}</textarea>
                <p>&nbsp;</p>

                <label for="product-description">Description</label>
                <textarea name="description" id="product-description-editor" class="form-control">{{$product->description}}</textarea>
                <p>&nbsp;</p>
				
				<?
					$i = 0;
				?>
				<? foreach($product->attributes()->get() as $attr):?>
					<? ++$i;?>
					<div class="customattribute">
						<label><?=$attr->attributename?> <a class="btn btn-danger btn-xxs removeattributebutton" href="#" title="Delete attribute"><i class="fa fa-fw fa-trash-o"></i></a></label>
						<input type="hidden" name="attribute<?=$i?>" value="<?=$attr->id?>">
						<input type="hidden" name="attributename<?=$i?>" value="<?=$attr->attributename?>">
						<textarea name="content<?=$i?>" class="form-control attributecontent"><?=$attr->pivot->content?></textarea>
						<p>&nbsp;</p>
					</div>
				<? endforeach;?>
								
				<input type="hidden" name="numattributes" id="numattributes" value="<?=$product->attributes()->count()?>">
				
				<div class="row" id="addattributerow">
					<div class="col-lg-3">
						<label for="productattribute">Select existing Attribute</label>
						{{ Form::select('productattribute', $product_attributes, null, array("class"=>"form-control", "id"=>"productattribute")) }}
					</div>
					<div class="col-lg-3">
						<label for="newproductattribute">or Enter new Attribute</label>
						<input type="text" id="newattribute" name="newattribute" value="" class="form-control">
					</div>
					<div class="col-lg-6">
						<label>&nbsp;</label><br>
						<button id="addattributebutton" type="button" class="btn btn-primary"><i class="fa fa-fw fa-plus"></i> Add</button>
					</div>
				</div>
				
				<div id="newattributetemplate" style="display:none">
					<div class="!customattribute!">
						<label>@attributename@ <a class="btn btn-danger btn-xxs removeattributebutton" href="#" title="Delete attribute"><i class="fa fa-fw fa-trash-o"></i></a></label>
						<input type="hidden" name="attribute@num@" value="@attributeid@">
						<input type="hidden" name="attributename@num@" value="@attributename@">
						<textarea name="content@num@" class="form-control !attributecontent!"></textarea>
						<p>&nbsp;</p>
					</div>
				</div>
			</div>
			
			<div class="tab-pane" id="images">
                <div class="row">
                    <div class="form-group col-lg-12">
                       	<div class="dropzone well" id="imagedropzone">
							<h3>Drop images here or&hellip;</h3>
							<span class="btn btn-success btn-sm fileinput-button">
								<span>Browse for images...</span>
								<!-- The file input field used as target for the file upload widget -->
								<input id="imageupload" type="file" name="theimage" data-url="{{URL::route("manager.products.uploadimage", $product->id)}}" multiple>
							</span>
						</div>
                    </div>
					
					<script id="tmpl-imagetypes" type="text/x-jsrender">
						{{ Form::select('productimagetype', $product_imagetypes, null, array("class"=>"form-control input-sm imagetypes")) }}
					</script>
					
					<script>
						$(function() {
							$('#imageupload').fileupload({
								dataType: 'json',
								type : "POST",
								autoUpload: false,
								maxFileSize: 2097152, // 2MB server limit
								sequentialUploads: true,
								acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
								disableImageResize: /Android(?!.*Chrome)|Opera/.test(window.navigator.userAgent),
								previewMaxWidth: 300,
								previewMaxHeight: 300,
								previewCrop: true,
								dropZone: $("#imagedropzone"),
								formData: {
									"_":"_" // dummy data to invoke correct route handler
								},
								done: function (e, data) {
									$(data.context).fadeOut("fast", function()
									{
										$(this).remove();
										$("#existingproductimages").load("{{URL::route("manager.products.getimages", $product->id)}}");
									});
								}
							}).on('fileuploadadd', function (e, data) {
								data.context = $('<div class="col-lg-2 imageuploaditem"/>').appendTo('#productimages');
								$.each(data.files, function (index, file) {
									var node = $('<p class="well text-center" />')
											.append($('<p/>').append($("<small/>").text(file.name)))
											.append($("#tmpl-imagetypes").render())
											.append($('<div class="progress progress-striped active"><div class="progress-bar progress-bar-success" role="progressbar" style="width: 0%;"></div>'))
											.append(uploadButton.clone(true).data(data));
									node.appendTo(data.context);
								});
							}).on('fileuploadprocessalways', function (e, data) {
								//console.log(data.index);
								var index = data.index,
									file = data.files[index],
									node = $(data.context.children()[index]);
								if (file.preview) {
									node
										.prepend('<br>')
										.prepend(file.preview);
								}
								if (index + 1 === data.files.length) {
									data.context.find('a')
										.text('Upload')
										.prop('disabled', !!data.files.error);
								}
							}).on("fileuploadsubmit", function(e, data) {
								
								var imagetypeid = data.context.find('.imagetypes').find("option:selected").val();
								data.formData = {"imagetypeid":imagetypeid};
																
							}).on('fileuploadprogress', function (e, data) {
								var progress = parseInt(data.loaded / data.total * 100, 10);
								var file = data.files[0];
								$(".progress-bar", data.context).css("width", progress+"%");
								//console.log(data.index);
								/*$('#progress .progress-bar').css(
									'width',
									progress + '%'
								);*/
							}).on('fileuploadprogressall', function (e, data) {
								var progress = parseInt(data.loaded / data.total * 100, 10);
								if(progress >= 100)
								{
									$("#existingproductimages").load("{{URL::route("manager.products.getimages", $product->id)}}");
									//document.location.href = document.location.href;
								}
							});
						});
					</script>
                </div>
				
				<div class="row" id="productimages"></div>
                
				<div class="row" id="existingproductimages">
					<? foreach($product->images()->get() as $img):?>
						<div class="col-lg-2 imageuploaditem">
							<div class="well text-center">
								<img src="<?=Croppa::url("/images/products/".$product->id."/".$img->imagefilename, 100)?>" class="img-thumbnail">
								<p><small><strong>Type</strong>: {{$img->imagetype()}}</small></p>
								<button type="button" class="btn btn-danger btn-xs btn-block deleteproductimage" data-url="{{URL::route("manager.products.deleteimage", array($product->id, $img->id) )}}"><i class="fa fa-fw fa-trash-o"></i> Delete</button>
							</div>
						</div>
					<? endforeach;?>
				</div>
				
            </div>
            <div class="tab-pane" id="files">
                <div class="row">
                    <div class="form-group col-lg-12">
                       	<div class="dropzone well" id="imagedropzone">
							<h3>Drop files here or&hellip;</h3>
							<span class="btn btn-success btn-sm fileinput-button">
								<span>Browse for files...</span>
								<!-- The file input field used as target for the file upload widget -->
								<input id="fileupload" type="file" name="thefile" data-url="{{URL::route("manager.products.uploadfile", $product->id)}}" multiple>
							</span>
						</div>
                    </div>
					
					<script id="tmpl-filetypes" type="text/x-jsrender">
						{{ Form::select('productfiletype', $product_filetypes, null, array("class"=>"form-control input-sm filetypes")) }}
					</script>

					<script>
						$(function() {
							$('#fileupload').fileupload({
								dataType: 'json',
								type : "POST",
								autoUpload: false,
								sequentialUploads: true,
								maxFileSize: 2097152, // 2MB server limit
								//acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
								//disableImageResize: /Android(?!.*Chrome)|Opera/.test(window.navigator.userAgent),
								//previewMaxWidth: 300,
								//previewMaxHeight: 300,
								//previewCrop: true,
								dropZone: $("#filedropzone"),
								formData: {
									"_":"_" // dummy data to invoke correct route handler
								},
								done: function (e, data) {
									$(data.context).fadeOut("fast", function()
									{
										$(this).remove();
										$("#existingproductfiles").load("{{URL::route("manager.products.getfiles", $product->id)}}");
									});
								},
								fail : function(e, data)
								{
									$(data.context).find(".progress").remove();
									$(data.context).find("p").append("<br><small class='label label-danger'>"+data.errorThrown+"</small>");
									//console.log(data);
								}
							}).on('fileuploadadd', function (e, data) {
								data.context = $('<div class="col-lg-2 fileuploaditem"/>').appendTo('#productfiles');
								$.each(data.files, function (index, file) {
									var node = $('<p class="well text-center" />')
											.append($('<p/>').append($("<small/>").text(file.name)))
											.append($("#tmpl-filetypes").render())
											.append($('<div class="progress progress-striped active"><div class="progress-bar progress-bar-success" role="progressbar" style="width: 0%;"></div>'))
											.append(uploadButton.clone(true).data(data));
									node.appendTo(data.context);
								});
							}).on('fileuploadprocessalways', function (e, data) {
								//console.log(data.index);
								var index = data.index,
									file = data.files[index],
									node = $(data.context.children()[index]);
								
								node
									.prepend('<br>')
									.prepend('<i class="fa fa-fw fa-file-o fa-5x"></i>');
								
								if (index + 1 === data.files.length) {
									data.context.find('a')
										.text('Upload')
										.prop('disabled', !!data.files.error);
								}
							}).on("fileuploadsubmit", function(e, data) {
								
								var filetypeid = data.context.find('.filetypes').find("option:selected").val();
								data.formData = {"filetypeid":filetypeid};
																
							}).on('fileuploadprogress', function (e, data) {
								var progress = parseInt(data.loaded / data.total * 100, 10);
								var file = data.files[0];
								$(".progress-bar", data.context).css("width", progress+"%");
								//console.log(data.index);
								/*$('#progress .progress-bar').css(
									'width',
									progress + '%'
								);*/
							}).on('fileuploadprogressall', function (e, data) {
								var progress = parseInt(data.loaded / data.total * 100, 10);
								if(progress >= 100)
								{
									$("#existingproductfiles").load("{{URL::route("manager.products.getfiles", $product->id)}}");
									//document.location.href = document.location.href;
								}
							});
						});
					</script>
                </div>
				
				<div class="row" id="productfiles"></div>
                
				<div class="row" id="existingproductfiles">
					<? foreach($product->files()->get() as $file):?>
						<div class="col-lg-2 fileuploaditem">
							<div class="well text-center">
								<i class="fa fa-fw fa-file-o fa-5x"></i><br>
								<p>
									<small><strong>{{$file->filename}}</strong><br />
									<strong>Type</strong>: {{$file->filetype()}}</small>
								</p>
								<button type="button" class="btn btn-danger btn-xs btn-block deleteproductfile" data-url="{{URL::route("manager.products.deletefile", array($product->id, $file->id) )}}"><i class="fa fa-fw fa-trash-o"></i> Delete</button>
							</div>
						</div>
					<? endforeach;?>
				</div>
            </div>
			
			<div class="tab-pane" id="relatedproducts">
				<div class="row">
					<div class="col-lg-4">
						<div class="form-group">
							<div class="input-group">
								<span class="input-group-addon">Filter by name</span>
								<input type="text" class="form-control" id="product-filter" placeholder="Filter by name" value="">
							</div>
						</div>
						
						<div class="well">
							<ul class='blocklist full connectable' id='available-products'>
							@foreach($unrelatedproducts as $unrelatedproduct)
								<li data-relatedproductid='{{$unrelatedproduct->id}}' data-productname="{{ $unrelatedproduct->name }}" class="product-list-item hide">
									<div class='blocklistitem clearfix'>
										<? if($unrelatedproduct->images()->whereRaw("typeid = 1")->count() >= 1):?>
											<img src="<?=Croppa::url("/images/misc/loading_image.png", 100)?>" data-src="<?=Croppa::url("/images/products/".$unrelatedproduct->id."/". $unrelatedproduct->images()->whereRaw("typeid = 1")->first()->imagefilename, 100)?>">
										<? endif;?>
										
										{{ $unrelatedproduct->name }}
									</div>
								</li>
							@endforeach
							</ul>
						</div>
					</div>
					
					<div class="col-lg-4" id="blocklist-container">
						<div class="well">
							<ul class='blocklist full connectable' id='related-products' data-productid='{{$product->id}}'>
							@foreach($relatedproducts as $relatedproduct)
								<li data-relatedproductid='{{$relatedproduct->id}}' data-productname="{{ $relatedproduct->name }}" class="product-list-item">
									<div class='blocklistitem clearfix'>
										<? if($relatedproduct->images()->whereRaw("typeid = 1")->count() >= 1):?>
											<img src="<?=Croppa::url("/images/products/".$relatedproduct->id."/". $relatedproduct->images()->whereRaw("typeid = 1")->first()->imagefilename, 100)?>">
										<? endif;?>
										
										{{ $relatedproduct->name }}
									</div>
								</li>
							@endforeach
							</ul>
						</div>
					</div>
				</div>
			</div>
			
            <div class="tab-pane" id="general">
               <div class="row">
                    <div class="form-group col-lg-2">
                        <label for="status">Status</label>
                        {{ Form::select('status', array("0"=>"Hidden", "1"=>"Active"), $product->status, array("class"=>"form-control")) }}
                    </div>
                    <div class="form-group col-lg-4">
                        <label for="categoryid[]">Product Categories</label>
                        {{ $product_categories }}
                    </div>
                </div>
            </div>
        </div>

        
        <div class="row">
            <div class="col-lg-12">
                <button type="submit" class="btn btn-primary btn-large">Save</button>
                <a href="{{ URL::route('manager.products.index') }}" class="btn btn-default btn-large">Cancel</a>
            </div>        
            
        </div>
 
    {{ Form::close() }}
 
@stop